<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { usePagination } from "@/hooks/usePagination"
import { formatDateTime } from "@/utils"
import { type FormInstance, type FormRules, ElMessage, type TabsPaneContext } from "element-plus"
import { orderallocationQuery, updateOrderallocationApi } from "@/api/outbound/outbound-list/index"
import { Search, Refresh } from "@element-plus/icons-vue"
import { sizeDate, Y, M, D, shortcuts } from "@/utils/dateSet"
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const loading = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const activeName = ref("one")
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
// #region 查看
const dialogVisible = ref<boolean>(false) // 弹出框
import { useUserStore } from "@/store/modules/user"
const userStore = useUserStore()
const tableData = ref<any>([])
const searchData = reactive({
  statusName: "",
  sku: "", // 套餐
  source: "", // 订单来源
  state: "",
  searchDate: [
    new Date(Y.value, M.value, D.value, 0, 0, 0).getTime() - 3600 * 1000 * 24 * 7,
    new Date(Y.value, M.value, D.value, 23, 59, 59)
  ]
})
//清除查询日期
const clearDate = (val: any) => {
  // console.log(val)
  if (!val) {
    searchData.searchDate = []
  }
}
const searchFormRef = ref<FormInstance | null>(null)
const Flag = ref<any>(1) // 第几轮
const getTableData = () => {
  loading.value = true
  orderallocationQuery({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    state: searchData.state || 0, // 状态
    status: searchData.statusName || undefined, // 跟进状态
    flag: Flag.value,
    sku: searchData.sku,
    source: searchData.source,
    start:
      searchData.searchDate && searchData.searchDate.length ? new Date(searchData?.searchDate[0]).getTime() : "" || "",
    end:
      searchData.searchDate && searchData.searchDate.length ? new Date(searchData?.searchDate[1]).getTime() : "" || ""
  }).then((res: any) => {
    loading.value = false
    tableData.value = res.data.orderList
    paginationData.total = res.data.total
    // console.log(res, "数据")
  })
}

const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
getTableData()
// 切换不同状态
const handleClick = (tab: TabsPaneContext) => {
  paginationData.currentPage = 1
  if (tab.paneName == "one") {
    Flag.value = 1
    formData.value.rounds = 1
  }
  if (tab.paneName == "two") {
    Flag.value = 2
    formData.value.rounds = 2
  }
  if (tab.paneName == "three") {
    Flag.value = 3
    formData.value.rounds = 3
  }
  getTableData()
}

const formData = ref<any>({
  formDataGJ: [{ userList: "", numberList: "" }],
  rounds: 1
})
const handleUpdate = () => {
  if (dataArr.value.length == 0) {
    ElMessage.error("请先选择订单")
  } else {
    dialogVisible.value = true
    formData.value.orderList = dataArr.value
  }

  // formData.value = JSON.parse(JSON.stringify(row)) // 赋值需要深拷贝
  console.log(dataArr.value.length, "分配")
}

// 改弹出框验证
const formRules: FormRules = reactive({
  callSuper: [{ required: true, trigger: "blur", message: "11" }]
})
const timetimetime = ref()
// 确认提交按钮
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      formData.value.startTime = formatDateTime(timetimetime.value[0])
      formData.value.endTime = formatDateTime(timetimetime.value[1])
      updateOrderallocationApi(formData.value).then(() => {
        ElMessage.success("分配成功")
        dialogVisible.value = false
        getTableData()
        clearSelect()
      })
    } else {
      return false
    }
  })
}
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  clearValidate()
  formData.value = {
    formDataGJ: [{ userList: "", numberList: "" }],
    rounds: 1
  }
}
// #endregion

//  #region 批量选择
const tableRef = ref<any>(null)
const dataArr = ref<any>([])
const handleSelectionChange = (val: any) => {
  dataArr.value = []
  if (val.length) {
    val.forEach((item: any) => {
      dataArr.value.push(item)
      console.log(dataArr.value)
    })
  }
}
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, {
  immediate: true
})
// #endregion

// #region 查找账号
import { useUserListStore } from "@/store/modules/userList"
const UserListArr = ref()
const UserStore = useUserListStore()
UserStore.getUserListFn()
watch(
  [() => UserStore.userListStore],
  (newValue) => {
    UserListArr.value = newValue.flat()
  },
  {
    immediate: true
  }
)
// #endregion

//  #region 点击添加分配
const addDomain = () => {
  formData.value.formDataGJ.push({
    userList: "",
    numberList: ""
  })
}
// #endregion

// #region 删除添加分配
const removeDomain = (item: any) => {
  if (formData.value.formDataGJ.length <= 1) {
    return false
  }
  formData.value.formDataGJ.splice(item, 1)
}
// #endregion

// #region 单选框禁用
const selectable = (row: any) => {
  if (row.statusName == "已完成") {
    return false
  } else if (row.statusName == "跟进中") {
    return false
  } else {
    return true
  }
}
// #endregion

// #region 分页也能多选
const getRowKeys = (row: any) => {
  return row.id
}

const clearSelect = () => {
  tableRef.value.clearSelection()
}
// #endregion

// #region 订单来源根据部门查团队
import { getqueryTeamName } from "@/api/team"
const queryTeamName = ref()
const TeamName = () => {
  getqueryTeamName({}).then((res: any) => {
    queryTeamName.value = res.data
    console.log(queryTeamName.value, "数据")
  })
}
TeamName()
// #endregion

// #region 套餐
// import { getComboDataApi1 } from "@/api/combo"
// const comboAll = () => {
//   //套餐持久化
//   getComboDataApi1({
//     page: 1,
//     size: 100000,
//     state: "",
//     team: ""
//   }).then((res: any) => {
//     comboList.value = res.data.packageList
//     // console.log(comboList.value, 111)
//   })
// }
// comboAll()
import { useComboStore } from "@/store/modules/combo"
const comboStore = useComboStore()
comboStore.getComoboFn()
const comboList = ref<any>([])
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
// #endregion

// #region 加密
const toHideString = (val: any, len: any) => {
  if (val.length == 2) {
    return `${val.substring(0, len)}*****${val.substring(val.length)}`
  } else {
    return `${val.substring(0, len)}*****${val.substring(val.length - len)}`
  }
}
// #endregion

// #region 订单状态
import { getOrdeCode } from "@/api/order"
const codeList = ref<any>([])
/**-------- */
const getCodeList = () => {
  getOrdeCode().then((res: any) => {
    console.log(res, 8888888888)
    codeList.value = res.data
  })
}
getCodeList()
// #endregion

// #region 套餐过滤
const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.sku) {
      celValue = item.name
    }
  })
  return celValue
}
// #endregion

//
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="searchDate" label="订单日期">
          <el-date-picker
            v-model="searchData.searchDate"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :size="sizeDate"
            :default-time="defaultTime1"
            @change="clearDate"
          />
        </el-form-item>
        <el-form-item prop="statusName" label="跟进状态">
          <el-select v-model="searchData.statusName" clearable placeholder="请选择" style="width: 200px">
            <el-option label="未分配" value="0" />
            <el-option label="跟进中" value="1" />
            <el-option label="未完成" value="2" />
            <el-option label="已完成" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item prop="source" label="订单来源" v-if="userStore.teamName == '' && userStore.department == ''">
          <el-select v-model="searchData.source" clearable filterable placeholder="请选择订单来源" style="width: 240px">
            <el-option v-for="item in queryTeamName" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sku" label="套餐">
          <el-select v-model="searchData.sku" clearable filterable placeholder="请选套餐" style="width: 240px">
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
        </el-form-item>
        <el-form-item prop="orderState" label="订单状态">
          <el-select v-model="searchData.state" clearable filterable placeholder="请选状态" style="width: 240px">
            <el-option v-for="item in codeList" :key="item.code" :label="item.state" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" element-loading-text="加载中..." shadow="never">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="第一轮" name="one" />
        <el-tab-pane label="第二轮" name="two" />
        <el-tab-pane label="第三轮" name="three" />
      </el-tabs>
      <div class="table-wrapper">
        <div style="margin-bottom: 10px">
          <el-button type="primary" @click="handleUpdate">创建拨打任务</el-button>
        </div>

        <el-table :data="tableData" ref="tableRef" @selection-change="handleSelectionChange" :row-key="getRowKeys">
          <el-table-column
            type="selection"
            width="50"
            :selectable="selectable"
            align="center"
            :reserve-selection="true"
          />
          <el-table-column type="index" label="序号" align="center" width="70px">
            <template #default="{ $index }">
              {{ (paginationData.currentPage - 1) * paginationData.pageSize + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="risk_time" label="开始时间" align="center" width="180">
            <template #default="scope">
              <el-text v-if="scope.row.startTime !== null" class="mx-1">
                {{ formatDateTime(scope.row.startTime) }}</el-text
              >
            </template>
          </el-table-column>
          <el-table-column prop="risk_time" label="结束时间" align="center" width="180">
            <template #default="scope">
              <el-text v-if="scope.row.endTime !== null" class="mx-1"> {{ formatDateTime(scope.row.endTime) }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="risk_time" label="分配时间" align="center" width="180">
            <template #default="scope">
              <el-text v-if="scope.row.time !== null" class="mx-1"> {{ formatDateTime(scope.row.time) }}</el-text>
            </template>
          </el-table-column>

          <el-table-column prop="source" label="订单来源" align="center" />
          <el-table-column prop="cardName" label="身份证姓名" align="center" width="100">
            <template #default="scope">
              <p>{{ toHideString(scope.row.cardName, 1) }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="cardId" label="身份证号" align="center">
            <template #default="scope">
              <p>{{ toHideString(scope.row.cardId, 3) }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="takeMobile" label="收货号码" align="center">
            <template #default="scope">
              <p>{{ toHideString(scope.row.takeMobile, 3) }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="sku" label="套餐" align="center" :formatter="formatterCombo" width="200" />
          <el-table-column prop="statusName" label="跟进状态" align="center" />
          <el-table-column prop="userName" label="跟进人" align="center" />
          <el-table-column prop="takeAddress" label="收货地址" align="center" show-overflow-tooltip />
          <el-table-column prop="state.state" label="订单状态" align="center" />
          <el-table-column prop="remark" label="备注" align="center" />

          <!-- <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 分配 -->
    <el-dialog v-model="dialogVisible" title="创建拨打任务" @close="resetForm" width="30%">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="real" label="任务总量">
          <el-text class="mx-1">{{ dataArr.length }}</el-text>
        </el-form-item>

        <el-form-item prop="searchDate" label="开始时间">
          <el-date-picker
            v-model="timetimetime"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>

        <el-form-item prop="peopel" label="分配方式">
          <el-select v-model="formData.type" clearable style="width: 240px" filterable>
            <el-option label="平均分配" value="1" />
            <el-option label="自由分配" value="2" />
          </el-select>
        </el-form-item>
        <div v-for="(item, index) in formData.formDataGJ" :key="index">
          <el-form-item :label="'跟进人' + index" :prop="'userList.' + index">
            <el-select v-model="item.userList" clearable placeholder="请选择跟进人" style="width: 240px" filterable>
              <el-option v-for="item in UserListArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <div v-if="formData.type == '2'">
            <el-form-item :label="'分配数量' + index" :prop="'numberList.' + index">
              <el-input v-model="item.numberList" placeholder="分配数量" style="width: 240px" />
              <br />
            </el-form-item>
          </div>
          <el-form-item>
            <el-button @click="addDomain()"> + </el-button>
            <el-button @click="removeDomain(index)"> – </el-button>
          </el-form-item>
        </div>
        <!--   <el-form-item
          v-for="(item, index) in formData.userList"
          :key="index"
          :label="'跟进人' + index"
          :prop="'userList.' + index"
        >
          <el-select v-model="item.value" clearable placeholder="请选择跟进人" style="width: 240px" filterable>
            <el-option v-for="item in UserListArr" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button style="margin: 0px 0px 0px 30px" class="mt-2" @click.prevent="removeDomain(item)"
            >删除跟进人</el-button
          >
        </el-form-item> -->
        <!-- <div v-if="formData.type == '2'">
          <el-form-item
            v-for="(item, index) in formData.numberList"
            :key="index"
            :label="'分配数量' + index"
            :prop="'numberList.' + index"
          >
            <el-input v-model="item.value" placeholder="分配数量" style="width: 240px" />
            <br />
            <el-button style="margin: 0px 0px 0px 30px" class="mt-2" @click.prevent="removeDomain(item)"
              >删除分配数量</el-button
            >
          </el-form-item>
        </div> -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
